package db

import (
  "context"
  "fmt"
  "go.mongodb.org/mongo-driver/mongo"
  "go.mongodb.org/mongo-driver/mongo/options"
  "go.mongodb.org/mongo-driver/mongo/readpref"
  "livefind/global"
  "livefind/utils/logger"
)

func init() {
  global.GVA_MONGO = newClient()
  err := global.GVA_MONGO.Ping(context.TODO(), readpref.Primary())
  if err != nil {
    logger.Fatal(err.Error(), err)
  } else {
    logger.Info("Connecting to MongoDB SUCCESS")
  }
}

func newClient() *mongo.Client {
  mo := global.GVA_CONFIG.Mongo
  mongoAddress := mo.IP + ":" + mo.Port
  uri := fmt.Sprintf("mongodb://%s:%s@%s", mo.UserName, mo.Password, mongoAddress)
  clientOptions := options.Client().ApplyURI(uri)
  client, err := mongo.Connect(context.TODO(), clientOptions)
  if err != nil {
    logger.Fatal(err.Error(), err)
  }
  return client
}

func Collection(database, collection string) *mongo.Collection {
  return global.GVA_MONGO.Database(database).Collection(collection)
}
